package kevin.framework.basic.controller;

import java.io.File;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONArray;

import kevin.framework.basic.common.emun.XlsCellDataTypeEnum;
import kevin.framework.basic.common.utils.DateUtils;
import kevin.framework.basic.common.xls.CustomCell;
import kevin.framework.basic.common.xls.CustomCellStyle;
import kevin.framework.basic.common.xls.IXlsOperator;
import kevin.framework.basic.common.xls.XlsCellData;
import kevin.framework.basic.common.xls.XlsConvertResult;
import kevin.framework.basic.domain.Func;
import kevin.framework.basic.domain.Menu;
import kevin.framework.basic.service.IBaseService;
import kevin.framework.basic.service.IFuncService;
import kevin.framework.basic.service.IMenuService;

/**
 * Generate by Kevin's CodeBuilder
 **/
@Controller
@RequestMapping(value = "/func")
public class FuncController extends ResetfulBaseController<Func, String> implements IXlsOperator<Func> {

    IFuncService funcService;

    @Resource(name = "menuService")
    IMenuService menuService;

    @Resource(name = "funcService")
    @Override
    public void setService(IBaseService<Func, String> service) {
        this.service = service;
        funcService = (IFuncService)service;
    }

    /*
     * 页面 views/base/entityPath 文件夹路径
     * ***/
    @Override
    public String setPageModelPath(HttpServletRequest request) {
        // TODO Auto-generated method stub
        return "base" + File.separator + entityPath;
    }

    @Override
    protected void onRequestPage(String pageName, HttpServletRequest request) throws Exception {
        if ("index".equals(pageName) || "form".equals(pageName)) {
            JSONArray menuJson = menuService.getMenuJsonByPid("0");
            request.setAttribute("menuJson", menuJson);
        }
    }

    @Override
    protected Map<String, Object> setListParams(HttpServletRequest request) throws Exception {
        Map<String, Object> prs = new HashMap<String, Object>();
        String menuId = request.getParameter("menuId");
        if (StringUtils.isNotEmpty(menuId)) {
            prs.put("menuId", menuId);
        }
        return prs;
    }

    @Override
    public String getImportSheetName(MultipartHttpServletRequest request) throws Exception {
        String sheetName = request.getParameter("sheetName");
        return sheetName;
    }

    @Override
    public int getImportStartRow(MultipartHttpServletRequest request) throws Exception {
        String dataStartRow = request.getParameter("dataStartRow");
        if (dataStartRow == null) {
            return 0;
        } else {
            return Integer.parseInt(dataStartRow);
        }
    }

    /**
     * 设置行转换bean需要用到的额外数据，如菜单名称转为菜单Id
     ***/
    @Override
    protected Map<Object, Object> setXlsConvertExtData(HttpServletRequest request) {
        Map<Object, Object> extMap = new HashMap<Object, Object>();
        List<Menu> listMenu = new ArrayList<Menu>();
        try {
            listMenu = menuService.selectAll();
        } catch (Exception e) {
            logger.error("", e);
        }
        for (Menu m : listMenu) {
            if (!extMap.containsKey(m.getMenuText())) {
                extMap.put(m.getMenuText(), m.getId());
            }
        }
        return extMap;
    }

    @Override
    protected MultipartFile getImportXlsfile(Map<String, MultipartFile> fileMap) {
        MultipartFile file = fileMap.get("funcfile");
        return file;
    }

    /***
     * 行数据转为实体bean rowData：行数据 reqParams：request中的请求参数 extDataMap：setXlsConvertExtData设置的扩展数据
     **/
    @Override
    public XlsConvertResult<Func> xlsImport(String[] rowData, Map<String, String[]> reqParams,
        Map<Object, Object> extDataMap) throws Exception {
        XlsConvertResult<Func> res = new XlsConvertResult<Func>();
        StringBuffer errBuffer = new StringBuffer();
        String menuText = StringUtils.trim(rowData[0]);
        String funcDesc = StringUtils.trim(rowData[1]);
        String funcCode = StringUtils.trim(rowData[2]);
        String isLog = StringUtils.trim(rowData[3]);

        if (StringUtils.isEmpty(menuText)) {
            errBuffer.append("菜单名称不能为空");
        }
        if (StringUtils.isEmpty(funcDesc)) {
            errBuffer.append("功能描述不能为空");
        }

        if (StringUtils.isEmpty(funcCode)) {
            errBuffer.append("功能代码不能为空");
        }

        if (StringUtils.isEmpty(isLog)) {
            errBuffer.append("是否记录日志不能为空");
        }

        if (errBuffer.length() == 0) {
            String menuId = String.valueOf(extDataMap.get(menuText));
            if (!StringUtils.isEmpty(menuId)) {
                Func f = new Func();
                f.setMenuId(menuId);
                f.setFuncDesc(rowData[1]);
                f.setFuncCode(rowData[2]);
                f.setIsLog("是".equals(rowData[3]) ? "1" : "0");
                f.setCreateTime(new Date());
                res.bean = f;
            } else {
                errBuffer.append("[" + menuText + "]菜单在系统中不存在！");
            }
        }
        res.error = errBuffer.toString();
        return res;
    }

    /**
     * 导出参数参数设置
     ***/
    @Override
    public Map<String, Object> setXlsExpQueryParams(HttpServletRequest request) throws Exception {
        Map<String, Object> prs = new HashMap<String, Object>();
        String funcDesc = request.getParameter("funcDesc");
        String menuId = request.getParameter("menuId");
        String idList = request.getParameter("idList");
        if (StringUtils.isNotEmpty(funcDesc)) {
            prs.put("funcDesc", URLDecoder.decode(funcDesc, "utf-8"));
        }
        if (StringUtils.isNotEmpty(menuId)) {
            prs.put("menuId", menuId);
        }
        if (StringUtils.isNotEmpty(idList)) {
            idList = URLDecoder.decode(idList, "utf-8");
            List<String> pks = new ArrayList<String>();
            String[] idTmpArr = idList.split(",");
            for (String id : idTmpArr) {
                pks.add(id);
            }
            prs.put("idList", pks);
        }
        return prs;
    }

    @Override
    public String setExportSheetName(HttpServletRequest request) throws Exception {
        return getLang("func_xlsName");
    }

    /**
     * 创建表头，如果是模板方式导出，则不需要
     **/
    @Override
    public List<CustomCell[]> setExportSheetTitle(HttpServletRequest request) throws Exception {
        List<CustomCell[]> list = new ArrayList<CustomCell[]>();
        CustomCell[] celssSec = new CustomCell[4];
        CustomCell[] celssFirst = new CustomCell[1];
        celssFirst[0] = new CustomCell("功能列表-" + DateUtils.formatCurrentDateTime("yyyy年MM月dd日"), celssSec.length, 0);
        list.add(celssFirst);
        celssSec[0] = new CustomCell("菜单名称", 0, 1);
        celssSec[1] = new CustomCell("功能描述", 0, 1);
        celssSec[2] = new CustomCell("功能代码", 0, 1);
        celssSec[3] = new CustomCell("是否记录日志", 0, 1);
        list.add(celssSec);
        return list;
    }

    /***
     * 按模板导出时候，设定导出模板
     ***/
    @Override
    protected FileInputStream setXlsModelFileInputStream(HttpServletRequest request) throws Exception {
        String modelfile = URLDecoder.decode(request.getParameter("modelfile"), "utf-8");
        File f = new File(request.getServletContext().getRealPath("/WEB-INF") + File.separator + modelfile);
        return new FileInputStream(f);
    }

    @Override
    public String setExportXlsFileName(HttpServletRequest request) throws Exception {
        return URLDecoder.decode(request.getParameter("fileName"), "utf-8");
    }

    /**
     * 将bean数据转为行的单元格数据
     **/
    @Override
    public XlsCellData[] xlsExport(Func bean, int row) throws Exception {
        XlsCellData[] datas = new XlsCellData[4];
        datas[0] = XlsCellData.getXlsCellData(bean.getExtFeildsMap().get("menuText"), XlsCellDataTypeEnum.cString);
        datas[1] = XlsCellData.getXlsCellData(bean.getFuncDesc(), XlsCellDataTypeEnum.cString);
        datas[2] = XlsCellData.getXlsCellData(bean.getFuncCode(), XlsCellDataTypeEnum.cString);
        datas[3] = XlsCellData.getXlsCellData(bean.getIsLog().equals("1") ? "是" : "否", XlsCellDataTypeEnum.cString);
        return datas;
    }

    /**
     * 返回null，采用默认样式
     **/
    @Override
    public CustomCellStyle createHeaderCellStyle(String title, int rowIndex) throws Exception {
        return null;
    }

    /**
     * 返回null，采用默认样式
     **/
    @Override
    public CustomCellStyle createBodyCellStyle(Func bean, XlsCellData cellData, String colTitle) throws Exception {
        return null;
    }

    /**
     * 用于添加总结行，总结列，返回null则无总结 行 /列
     **/
    @Override
    public XlsCellData[] onSheetCreateCompleted(Object[] dataArr, int rowCount, int rowNum) throws Exception {
        return null;
    }

}
